package com.erps.config.Sys;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.erps.CommonUtils.ActionResult;
import com.erps.CommonUtils.AppConfig;
import com.erps.CommonUtils.Md5Util;
import com.erps.CommonUtils.Sequence;
import com.erps.CommonUtils.StringEx;
import com.erps.CommonUtils.UploadInfo;
import com.erps.CommonUtils.UploadPostFiles;
import com.erps.CommonUtils.Validity;
import com.erps.CommonUtils.ValueType;
import com.erps.sys.rest.ErspSysOrgRest;
import com.erps.sys.rest.ErspSysUserRest;
import com.hmkj.entity.ErspSysUser;
import com.hmkj.entity.vo.LoginUserInfo;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

/**
 * SystemController
 */
public class SystemController extends Controller {
	private static final Logger log = LoggerFactory.getLogger(SystemController.class);

	// 获取注册单位列表
	public void regist01() {
		ErspSysOrgRest vs = new ErspSysOrgRest();
		List<Map<String, String>> dtOrgList = vs.QueryAsMap();
		setAttr("org_list", dtOrgList);
		this.render("regist01.ftl");
	}

	public void regist02() {
		this.render("regist02.ftl");
	}

	public void regist03() {
		this.render("regist03.ftl");
	}

	public void upload() {
		render("upload.ftl");
	}

	public void login() {
		Cookie[] cks = this.getRequest().getCookies();
		System.out.println("系统中包含Cookie列表:");
		for (int i = 0; (cks != null) && (i < cks.length); i++) {
			System.out.println(cks[i].toString());
		}
		this.render("login.ftl");
	}

	public void ersp_sys_org_user() {
		ErspSysUser vo = new ErspSysUser();
		ErspSysUserRest rest = new ErspSysUserRest();
		HttpServletRequest request = this.getRequest();
		vo.setId(StringEx.getStr(this.getPara("id")));
		vo.setUser_identity(StringEx.getStr(this.getPara("user_identity")));
		vo.setUser_phone(StringEx.getStr(this.getPara("user_phone")));
		vo.setOrg_id(StringEx.getStr(this.getPara("org_id")));
		vo.setUser_mailaddr(StringEx.getStr(this.getPara("user_mailaddr")));

		String cTelNo = StringEx.getStr(vo.getUser_phone());
		String cMailNO = StringEx.getStr(vo.getUser_mailaddr());
		ActionResult ret = ActionResult.Valid(ValueType.FAILURE);

		String cuser_keyword = StringEx.getStr(this.getPara("user_keyword"));
		String cuser_password = StringEx.getStr(this.getPara("user_password"));

		if (!Validity.isMobile(cTelNo)) {
			ret = ActionResult.Valid("user_phone", "手机号码格式错误！");
			renderJson(JSON.toJSONString(ret));
		} else if (!Validity.isEmail(cMailNO)) {
			ret = ActionResult.Valid("user_mailaddr", "邮箱账号格式错误！");
			renderJson(JSON.toJSONString(ret));
		} else if ((!cuser_keyword.equals(cuser_password)) && (cuser_keyword.length() > 0)) {
			ret = ActionResult.Valid("user_keyword", "密码和验证码格式错误！");
			renderJson(JSON.toJSONString(ret));
		} else {
			vo.setId(Sequence.getGuid());
			vo.setUser_checked("0");
			String cStr = Md5Util.MD5(cuser_keyword);
			vo.setUser_passhash(Md5Util.MD5(cStr + AppConfig.MD5_KEY));
			int iCode = rest.add(vo);
			if (iCode > 0)
				ret = ActionResult.Valid(ValueType.SUCCESS);
			else
				ret = ActionResult.Valid(ValueType.FAILURE);
			renderJson(JSON.toJSONString(ret));
		}
	}

	public void userlogin() {
		log.debug("进入登录");
		String cUserID = getPara("UserID");
		String cKeyWord = getPara("KeyWord");
		String cValidateCode = this.getPara("ValidateCode");
		ActionResult ret = new ActionResult();

		HttpServletRequest request = this.getRequest();
		HttpServletResponse response = this.getResponse();

		ret = ActionResult.Valid(ValueType.FAILURE);
		// HttpSession session = request.getSession();
		// String cValue = StringEx.getStr(session.getAttribute("rand"));
		// if ((cValue.length() == 0) || (!cValue.equals(cValidateCode))) {
		// ret.setCode(2);
		// ret.setMessage("验证码错误！");
		// log.info(ret.getMessage());
		// renderJson(ret);
		// return;
		// }

		ErspSysUserRest vUser = new ErspSysUserRest();
		ErspSysUser vo = vUser.LoginQuery(cUserID);
		if (vo == null) {
			ret = ActionResult.Valid("数据库连接失败！");
			System.out.println("数据库连接失败！");
		} else {
			String cStr = Md5Util.MD5(cKeyWord);
			String cKeyHash = Md5Util.MD5(cStr + AppConfig.MD5_KEY);
			if (cKeyHash.equals(vo.getUser_passhash())) {

				LoginUserInfo vUserInf = new LoginUserInfo();
				vUserInf.setUserID(cUserID);
				vUserInf.setOrgID(vo.getOrg_id());
				vUserInf.setUserName(vo.getUser_identity());
				vUserInf.setUserGuid(vo.getId());
				vUserInf.setOrgName(new ErspSysOrgRest().FindOne(vo.getOrg_id()).getOrg_name());

				try {
					// 设置cookie有效期为1天
					Cookie ckUserID = new Cookie(AppConfig.SESSION_USERID, vUserInf.getUserID());
					ckUserID.setMaxAge(60 * 60 * 24);
					response.addCookie(ckUserID);

					Cookie ckUserName = new Cookie(AppConfig.SESSION_USERNAME, vUserInf.getUserName());
					ckUserName.setMaxAge(60 * 60 * 24);
					response.addCookie(ckUserName);

					Cookie ckOrgID = new Cookie(AppConfig.SESSION_ORGID, vUserInf.getOrgID());
					ckOrgID.setMaxAge(60 * 60 * 24);
					response.addCookie(ckOrgID);

					Cookie ckOrgName = new Cookie(AppConfig.SESSION_ORGNAME, vUserInf.getOrgName());
					ckOrgName.setMaxAge(60 * 60 * 24);
					response.addCookie(ckOrgName);
					System.out.print("向Cookie写入:AppConfig.SESSION_USERID");
				} catch (Exception ex) {
					ex.printStackTrace();
					System.out.print("向Cookie写入失败");
				}

				setSessionAttr(AppConfig.SESSION_USERID, vUserInf.getUserID());
				setSessionAttr(AppConfig.SESSION_USERNAME, vUserInf.getUserName());
				setSessionAttr(AppConfig.SESSION_ORGID, vUserInf.getOrgID());
				setSessionAttr(AppConfig.SESSION_USERGUID, vUserInf.getUserGuid());
				setSessionAttr(AppConfig.SESSION_ORGNAME, vUserInf.getOrgName());

				ret = ActionResult.Valid(ValueType.SUCCESS);
				renderJson(JSON.toJSONString(ret));
				System.out.println("用户登录成功！");
			} else {
				ret = ActionResult.Valid("账户或密码错误！");
				System.out.println("账户或密码错误！");
			}
		}
		renderJson(JSON.toJSONString(ret));
	}

	public void ValidateCode() throws IOException {
		Date v = new Date();
		HttpServletResponse response = this.getResponse();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 13 * i + 6, 16);
		}
		HttpSession session = this.getRequest().getSession();
		session.setAttribute("rand", sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
		render("framework/validate.jsp?id=" + v);
	}

	Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
